package com.quxiu.system.service.impl;

import com.quxiu.common.redis.service.RedisService;
import com.quxiu.system.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class IdServiceImpl implements IdService {
    private static final String KEY_WORKER_ID_BIND = "worker_id:bind:";
    private static final String KEY_WORKER_ID_SEQ = "worker_id:seq:";
    private static final long CACHE_EXPIRES = 60 * 5;

    // 开始时间截 (2023-01-01)
    private static final long START_TIMESTAMP = 1672531200000L;

    // 数据中心ID位数
    private static final long DATACENTER_ID_BITS = 5L;
    // 机器ID位数
    private static final long WORKER_ID_BITS = 5L;
    // 序列号位数
    private static final long SEQUENCE_BITS = 12L;

    // 数据中心ID左移位数
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS;
    // 机器ID左移位数
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS + DATACENTER_ID_BITS;
    // 时间戳左移位数
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + DATACENTER_ID_BITS + WORKER_ID_BITS;

    // 生成序列的掩码，这里为4095 (0b111111111111=0xfff)
    private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);

    // 毫秒内序列(0~4095)
    private long sequence = 0L;
    // 上次生成ID的时间截
    private long lastTimestamp = -1L;
    // 最大数据中心ID
    private static final long maxDatacenterId = -1L ^ (-1L << DATACENTER_ID_BITS);
    // 最大机器ID
    private static final long maxWorkerId = -1L ^ (-1L << WORKER_ID_BITS);

    @Resource
    private RedisService redisService;

    private String workIp;
    private long workerId;
    private long dataCenterId = 0L;

    /**
     * 初始化
     */
    @PostConstruct
    private void init() {
        try {
            this.workIp = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("IdGenerator 获取本机IP地址失败");
            throw new RuntimeException(e);
        }

        this.createGenerator();
        this.daemon();
    }

    /**
     * 销毁
     */
    @PreDestroy
    private void destroy() {
        String bindKey = KEY_WORKER_ID_BIND + workIp;
        String seqKey = KEY_WORKER_ID_SEQ + workerId;
        redisService.deleteObject(bindKey);
        redisService.deleteObject(seqKey);
    }

    private void createGenerator() {
        sequence = 0L;
        lastTimestamp = -1L;
        this.workerId = getWorkerId();
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (this.dataCenterId > maxDatacenterId || this.dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
    }

    /**
     * 获取下一个ID
     *
     * @return 下一个ID
     */
    @Override
    public synchronized long nextId() {
        long timestamp = timeGen();

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            // 毫秒内序列溢出
            if (sequence == 0) {
                // 阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 时间戳改变，毫秒内序列重置
            sequence = 0L;
        }

        // 上次生成ID的时间截
        lastTimestamp = timestamp;

        // 移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) |
                (this.dataCenterId << DATACENTER_ID_SHIFT) |
                (this.workerId << WORKER_ID_SHIFT) |
                sequence;
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     *
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     *
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * 获取workerId
     * @return workerId
     */
    private Long getWorkerId() {
        String bindKey = KEY_WORKER_ID_BIND + this.workIp;
        Long workerId = redisService.getCacheObject(bindKey);
        if (workerId != null) {
            return workerId;
        }
        for (long i = 0; i < maxWorkerId - 1; i++) {
            String seqKey = KEY_WORKER_ID_SEQ + i;
            if (redisService.setCacheObjectIfAbsent(seqKey, this.workIp, CACHE_EXPIRES, TimeUnit.SECONDS)) {
                workerId = i;
                break;
            }
        }
        if (workerId != null) {
            redisService.setCacheObject(bindKey, workerId, CACHE_EXPIRES, TimeUnit.SECONDS);
            return workerId;
        } else {
            throw new RuntimeException("获取workerId失败");
        }
    }

    /**
     * 守护线程，用于检查是否需要重新获取workerId
     */
    private void daemon() {
        // 线程
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    log.debug("IdGenerator daemon() run.");
                    Thread.sleep(1000 * 5);

                    String bindKey = KEY_WORKER_ID_BIND + workIp;
                    String seqKey = KEY_WORKER_ID_SEQ + workerId;

                    Long workerId = redisService.getCacheObject(bindKey);
                    if (workerId != null) {
                        redisService.setCacheObject(seqKey, workIp, CACHE_EXPIRES, TimeUnit.SECONDS);
                        redisService.setCacheObject(bindKey, this.workerId, CACHE_EXPIRES, TimeUnit.SECONDS);
                    } else {
                        this.createGenerator();
                    }

                } catch (InterruptedException e) {
                    log.error("IdGenerator daemon() error:", e);
                }
            }
        });
        thread.start();
    }

}
